﻿/* Copy Write: AulacSoft */
/* Author write: Thangnc */
/* Code date: 12/17/2010 */

using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Linq;

using System.Collections.Generic;
using Aulac.Global.Enums; 
using Aulac.Global.Data;
using Aulac.Global.Common; 
using Aulac.Global.Xml;
using Aulac.Rsc.Ems; 
using Aulac.Rsc.Ems.Tags;
using Aulac.Srv.Db.Data.Ems.Stores;
using Aulac.Srv.Db.Provider; 
using Aulac.Srv.Db.Connect;
using Aulac.Srv.Db.Data.Ems.InvJrns;
using Aulac.Srv.Db.Data.Ems.AcntJrns;
using Aulac.ErrCodes;
using Aulac.Srv.Db.Common;
using Aulac.Global.Exceptions;
using Aulac.Rsc;
using Aulac.Srv.Db.Data.Ems.AcntJrns.Xml;
using Aulac.Srv.Db.Data.Ems.Global;
using Aulac.Srv.Db.Data.Ems.AcntJrns.Acnt;
using Aulac.Srv.Db.Data.Ems.Stores.InOutputStores;

namespace Aulac.Srv.Db.Data.Ems.Stores.RelsStores
{
	/// <summary>
	/// Quan ly mua hang, nhap kho, xuat kho noi bo
	/// </summary>
    public partial class VchRelsStoreMng : Aulac.Srv.Db.Data.Ems.Document.DbEmsDataDocumentMangager, IVchRelsStoreMng, Aulac.Srv.Db.Data.Ems.Interface.IVchSyncJrn
	{
        IAcntJrnMng mAcntJrn = null;
        public VchRelsStoreMng(IDbAulacConnect p_Db)
            : base(p_Db)
        {
           // mAcntJrn = new AcntJournal(p_Db); 
        }

        public VchRelsStoreMng(IDbAulacConnect p_Db, IAcntJrnMng pAcntJrn)
            : base(p_Db)
        {
            mAcntJrn = pAcntJrn;
        }

        #region Overrider Methods
       
        /// <summary>
        /// Them mot chung tu vao VStoreVoucher
        /// </summary>
        /// <param name="mDbCmd"></param>
        /// <param name="xmlDoc"></param>
        /// <returns></returns>
        protected override bool OnAddVoucher( ref XmlDataDocument xmlDoc)
        {
            /* Code date: 12/17/2010 by Thangnc*/
            
            try
            {
                string sVchID = "", sVchType = "";
                XmlElement eVch = XmlProcess.GetVchElm(xmlDoc);
                
                AddVchStoreHeader(eVch, ref sVchID, ref sVchType);
                XmlElement eLines = XmlProcess.GetVchLinesElm(xmlDoc);
               
                AddVListStoreLine( XmlProcess.GetListVchLineItem(xmlDoc), sVchID);

                XmlDataDocument xmlQtyLost = null;
                if (!UpdateInvJournal(xmlDoc, out xmlQtyLost) && xmlQtyLost != null)
                    throw new AulacException(ErrorCode.Error0010, xmlQtyLost.OuterXml, "");
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Cap nhat mot chung tu vao VStoreVoucher
        /// </summary>
        /// <param name="mDbCmd"></param>
        /// <param name="xmlDoc"></param>
        /// <returns></returns>
        protected override bool OnUpdateVoucher( ref XmlDataDocument xmlDoc)
        {
            /* Code date: 12/17/2010 by Thangnc*/

            /*Update mot chung tu kho
             * Kiem tra xem trong XmlDoc da co voucherID da co chua? 
             * 1.Neu co --> Update chung tu
             * 2. Neu chua --> Goi Ham AddVoucher de them chung tu vao kho
             */
            XmlElement eVch = XmlProcess.GetVchElm(xmlDoc);
            string sVchID = "", sVchType = "";
            UpdateVchStoreHeader(eVch, ref sVchID, ref sVchType);
            DelVchStoreLineDb(sVchID);
            AddVListStoreLine(XmlProcess.GetListVchLineItem(xmlDoc), sVchID);

            XmlDataDocument xmlQtyLost = null;
            if (!UpdateInvJournal(xmlDoc, out xmlQtyLost) && xmlQtyLost != null)
                throw new AulacException(ErrorCode.Error0010, xmlQtyLost.OuterXml, "");

            return true;
        }

        /// <summary>
        /// Xoa mot chung tu kho voi VoucherID , VoucherType chua trong Param
        /// </summary>
        /// <param name="mDbCmd"></param>
        /// <param name="xmlDoc">Chua Voucher can xoa</param>
        /// <returns></returns>
        protected override bool OnDelVoucher( ref XmlDataDocument xmlDoc)
        {
            /* Code date: 12/17/2010 by Thangnc*/

            string sVoucherID = XmlProcess.GetValueParam(xmlDoc, tagVch.Inv.VchRelsInvPrkID);
            string sVoucherType = XmlProcess.GetValueParam(xmlDoc, tagVch.Inv.VchTypeID);
            bool isCheckQtyLost = XmlProcess.GetValueParamBoolean(xmlDoc, tagVch.Inv.IsCheckQtyLost);
            DelVchStoreDb(sVoucherID, sVoucherType, isCheckQtyLost);
            return true;// mAcntJrn.DeleteAcntJrn(sVoucherID, sVoucherType);
        }


        protected override void OnGetListVoucher(ref DataTable pDataReturn, XmlDataDocument xmlParam)
        {
            /* Author Write: H.Rin */
            /* Code Update: 01/05/2011 */
            
            string str = StringHelper.ConvertArrayToString(", h.", VchRelsStoreInfo.mListRelsVchH.ToArray());
            str = "h." + str;
            string str1 = str + string.Format(", SUM(l.{0}) as {1}", tagVch.Inv.AmtSumInExc, tagVch.Inv.AmtSumInExc);
            //sqlQuery = string.Format("SELECT {0} FROM {1} h INNER JOIN {2} l ", str, TableNames.VchRelsInvHeader, TableNames.VchRelsInvLine);
            //sqlQuery += string.Format(" ON h.{0} = l.{1}", tagVch.Inv.VchRelsInvPrkID, tagVch.Inv.VchRelsInvPrkID);

            sqlQuery += string.Format("SELECT DISTINCT Rh.{0}, ", StringHelper.ConvertArrayToString(", Rh.", VchRelsStoreInfo.mListRelsVchH));
            sqlQuery += string.Format(" S.{0} AS {1}, ", tagItems.Store.StoreName, tagVch.Inv.StoreRelsName);
            sqlQuery += string.Format(" TsType.{0} ", tagItems.Store.TagStoreTypeName);
                                  
            sqlQuery += string.Format(" FROM {0} AS Rh ", TableNames.VchRelsInvHeader);
            sqlQuery += string.Format(" LEFT OUTER JOIN {0} AS Rl ON Rh.{1} = Rl.{1}", TableNames.VchRelsInvLine, tagVch.Inv.VchRelsInvPrkID);
            sqlQuery += string.Format(" LEFT OUTER JOIN {0} AS TsType ON Rh.{1} = TsType.{2}", TableNames.Dm_TagStoreTypes, tagVch.Inv.TagStoreTypeID, tagItems.Store.TagStoreTypeID);
            sqlQuery += string.Format(" LEFT OUTER JOIN {0} AS S ON Rh.{1} = S.{2}", TableNames.Dm_MdnStores, tagVch.Inv.StorePrkID, tagItems.Store.StorePrkID);


            sqlQuery += string.Format(" WHERE (Rh.{0} BETWEEN ? AND ?)", tagVch.Inv.VchDate);
            sqlQuery += string.Format("  AND (? IS NULL  OR Rh.{0} = ?)", tagVch.Inv.VchTypeID);
            //sqlQuery += string.Format(" GROUP BY {0}", str);
            //sqlQuery += string.Format(" ORDER BY Rh.{0}, h.{1}, Rh.{2}", tagVch.Inv.VchDate, tagVch.Inv.VchNo, tagVch.Inv.VchRelsInvPrkID);

            string fromDate = XmlProcess.GetValueParam(xmlParam, tagVch.Inv.VchDateFrom);
            string toDate = XmlProcess.GetValueParam(xmlParam, tagVch.Inv.VchDateTo);
            string voucherType = XmlProcess.GetValueParam(xmlParam, tagVch.Inv.VchTypeID);

            //DbDataReader = DbDataProvider.ExecuteReader(mDbCmd, sqlQuery, fromDate, toDate, voucherType,  voucherType);
            XmlDataDocument xmlDoc = CreateXmlDocument("", "");
            XmlElement eHeader = XmlProcess.AddVchHeaderElm(ref xmlDoc);
            XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.VchDateFrom, fromDate);
            XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.VchDateTo, toDate);
            XmlElement eLines = XmlProcess.AddVchLinesElm(ref xmlDoc);
            //DbDataProvider.SelectValuesToChildXml(mDbCmd, sqlQuery, new object[] { fromDate, toDate, voucherType, voucherType }, ref eLines, tagCtrl.LINE);
            DbDataProvider.ExecuteReaderDataToTable(mDbCmd, sqlQuery, ref pDataReturn, fromDate, toDate, voucherType, voucherType);
        }
        
        protected override XmlDataDocument OnGetVoucher(XmlDataDocument xmlParam)
        {
            /* Code date: 12/17/2010 by Thangnc*/

            string sVoucherID = XmlProcess.GetValueParam(xmlParam, tagVch.Inv.VchRelsInvPrkID);
            return GetVchStoreDb(sVoucherID);
        }
        #endregion
       
        #region IVchInStock Members

        public void SyncPrimeCostForVch(string pOrgVchID, string pVchTypeID)
        {
            /* Code date: 12/17/2010 by Thangnc*/

            string[] arr = new string[] { tagVch.Inv.PrimeCostInExc, tagVch.Inv.AmtPrimeCostLineInExc };

            IInvJrnMng invInfo = new InvJrnMng(this.DbDataProvider.DbAulacConnection);
            DataTable tbInvJrn = invInfo.GetPrimeCostOfVch(pOrgVchID, pVchTypeID);
            sqlQuery = SqlHelper.CreateSqlUpdate(TableNames.VchRelsInvLine, arr);
            sqlQuery = string.Format(" WHERE ({0} = ?) AND ({1} = ? ) AND ({2} = )", tagVch.Inv.VchRelsInvPrkID, tagVch.Inv.StorePrkID, tagVch.Inv.ItemPrkID);

            foreach (DataRow row in tbInvJrn.Rows)
            {
                double dPrimeCostInExc = Aulac.Global.Data.DataTableProcess.GetValueNumber(row, tagVch.Inv.PrimeCostInExc);
                List<object> list = new List<object>();
                list.Add(dPrimeCostInExc);
                list.Add(string.Format("{0} * {1}", tagVch.Inv.Quantity, dPrimeCostInExc));
                list.Add(pOrgVchID);
                list.Add(Aulac.Global.Data.DataTableProcess.GetValue(row, tagVch.Inv.StorePrkID));
                list.Add(Aulac.Global.Data.DataTableProcess.GetValue(row, tagVch.Inv.ItemPrkID));
                DbDataProvider.ExecuteNonQuery(ref mDbCmd, sqlQuery, list.ToArray());
            }
        }
        public void ReUpdateAcntJrn(IAcntJrnMng pAcntJrn, string pVchRelsInvPrkID, string pVchType)
        {
            /* Code date: 12/17/2010 by Thangnc*/

            XmlDataDocument xmlDoc = CreateXmlAcntJrn(pVchRelsInvPrkID);
            if (xmlDoc == null)
            {
                pAcntJrn.DeleteAcntJrn(pVchRelsInvPrkID, pVchType);
                return;
            }
            else
            {
                pAcntJrn.SetAcntJrn(ref xmlDoc);
            }
        }

        

        #endregion
        
        #region IVchRelsStoreMng Members

        public XmlDataDocument GetNewVchNo(XmlDataDocument xmlParam)
        {
            /* Code date: 12/17/2010 by Thangnc*/

            string sVchTypeID = XmlProcess.GetValueParam(xmlParam, tagVch.Inv.VchTypeID);
            XmlDataDocument xmlOutDoc = CreateXmlDocument("", "");
            string sVchName = "";
            string sVchNo = GetNewVchNoDb(sVchTypeID, ref sVchName);
            XmlProcess.SetAtrbVchHeader(xmlOutDoc, tagVch.Inv.VchNo, sVchNo);
            XmlProcess.SetAtrbVchHeader(xmlOutDoc, tagVch.Inv.VchName, sVchName);
            return xmlOutDoc;
        }      
        #endregion
    }
}
